/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015-1-31         yellowlgx
 */

package com.skyworth.ui.api;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.skyworth.commen.ui.R;
import com.skyworth.theme.SkyThemeEngine;
import com.skyworth.theme.widget.IThemeable;
import com.skyworth.ui.blurbg.BlurBgLayout;
import com.skyworth.ui.define.SkyTextSize;
import com.skyworth.util.MyFocusFrame;
import com.skyworth.util.SkyScreenParams;

/**
 * @author yellowlgx
 * @ClassName SkyDialogView
 * @Description <p>
 * 系统弹出框公共类，其实质是一个layout，并不是弹出框。 public SkyDialogView(Context context, boolean
 * twoBtn)boolean twoBtn参数表示true显示两个按钮，false反之； 其中show()，dismiss()方法齐全，设置文字分为两行设置
 * public void setTipsString(String tips_1, String
 * tips_2)，可传null值，由于需要计算每行文字长度来决定显示的位置，所以在每次show()的时候都需要调用setTipsString(String tips_1,
 * String tips_2)，这里略坑，但是没有办法。。
 * </p>
 * @date 2015-1-31
 */
public class SkyDialogViewV1 extends FrameLayout implements IThemeable
{
    private Context mContext;
    protected FrameLayout contentView;
    private LinearLayout content;
    protected TextView tipsView_1, tipsView_2;// 名称
    protected TextView firstBtn, secondBtn; // 按钮
    protected BlurBgLayout blurBgLayout;

    private int shaderSize = 0, unfocusShaderSize = 0;
    private MyFocusFrame focusView;
    private boolean twoBtn = true;
    private boolean isTwoString = false;

    private AnimationSet animSet;
    private TranslateAnimation transAnim;
    private AlphaAnimation alphaAnim;

    private OnDialogOnKeyListener mListener;

    private int mInitBtnFocusIndex = 0;

    public interface OnDialogOnKeyListener
    {
        public boolean onDialogOnKeyEvent(int keyCode, KeyEvent event);

        public void onFirstBtnOnClickEvent();

        public void onSecondBtnOnClickEvent();
    }

    public SkyDialogViewV1(Context context, boolean twoBtn)
    {
        super(context);
        this.twoBtn = twoBtn;
        mContext = context;
        shaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(93);
        unfocusShaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(12);
        initView();
    }

    public SkyDialogViewV1(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mContext = context;
        shaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(93);
        unfocusShaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(12);
        initView();
    }

    public SkyDialogViewV1(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        mContext = context;
        shaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(93);
        unfocusShaderSize = SkyScreenParams.getInstence(mContext).getResolutionValue(12);
        initView();
    }

    public void setOnDialogOnKeyListener(OnDialogOnKeyListener listener)
    {
        mListener = listener;
    }

    private void initView()
    {
        initAnim();
        this.setFocusable(false);
        this.setLayoutParams(
                new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        contentView = new FrameLayout(mContext);
        contentView.setFocusable(false);
        // contentView.setBackgroundColor(Color.CYAN);
        contentView.setBackgroundResource(R.drawable.ui_sdk_dialog_shadow);

        LayoutParams content_p = new LayoutParams(
                SkyScreenParams.getInstence(mContext).getResolutionValue(1061) + shaderSize * 2,
                SkyScreenParams.getInstence(mContext).getResolutionValue(492) + shaderSize * 2);
        content_p.gravity = Gravity.CENTER;
        this.addView(contentView, content_p);

        blurBgLayout = new BlurBgLayout(mContext);
        blurBgLayout.setPageType(BlurBgLayout.PAGETYPE.OTHER_PAGE);
        blurBgLayout.setBgAlpha(1.0f);
        contentView.addView(blurBgLayout,
                new LayoutParams(
                        SkyScreenParams.getInstence(mContext).getResolutionValue(1061),
                        SkyScreenParams.getInstence(mContext).getResolutionValue(492),
                        Gravity.CENTER));

        focusView = new MyFocusFrame(mContext,
                SkyScreenParams.getInstence(mContext).getResolutionValue(83) - unfocusShaderSize);
        focusView.needAnimtion(true);
        focusView.setImgResourse(R.drawable.ui_sdk_btn_focus_shadow_no_bg);

        LayoutParams focus_p = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        this.addView(focusView, focus_p);

        tipsView_1 = new TextView(mContext);
        tipsView_1.setText(" ");
        tipsView_1.setFocusable(false);
        tipsView_1.setLineSpacing(SkyScreenParams.getInstence(mContext).getResolutionValue(13), 1);
        tipsView_1.setTextSize(
                SkyScreenParams.getInstence(mContext).getTextDpiValue(SkyTextSize.t_5));
        tipsView_1.setTextColor(getResources().getColor(R.color.c_4));
        tipsView_1.setEllipsize(TruncateAt.END);
        tipsView_1.setGravity(Gravity.CENTER);
        tipsView_1.setVisibility(View.GONE);

        tipsView_2 = new TextView(mContext);
        tipsView_2.setFocusable(false);
        tipsView_2.setTextSize(
                SkyScreenParams.getInstence(mContext).getTextDpiValue(SkyTextSize.t_3));
        tipsView_2.setTextColor(getResources().getColor(R.color.c_3));
        tipsView_2.setGravity(Gravity.CENTER);
        tipsView_2.setVisibility(View.GONE);

        firstBtn = new TextView(mContext);
        firstBtn.setFocusable(true);
        firstBtn.setFocusableInTouchMode(true);
        firstBtn.setId(R.id.sky_dialog_btn_1);
        firstBtn.setGravity(Gravity.CENTER);
        firstBtn.setSingleLine(true);
        firstBtn.setHorizontallyScrolling(true);
        firstBtn.setEllipsize(TruncateAt.MARQUEE);
        firstBtn.setMarqueeRepeatLimit(-1);
        firstBtn.setText(R.string.dialog_btn_1);
        firstBtn.setTextSize(
                SkyScreenParams.getInstence(mContext).getTextDpiValue(SkyTextSize.t_4));
        firstBtn.setTextColor(getResources().getColor(R.color.c_3));
        firstBtn.setOnKeyListener(onKeyListener);
        firstBtn.setOnClickListener(clickListener);
        firstBtn.setOnFocusChangeListener(changeListener);
        firstBtn.setBackground(SkyThemeEngine.getInstance()
                .getDrawable(R.drawable.ui_sdk_btn_unfocus_big_shadow, false));

        secondBtn = new TextView(mContext);
        secondBtn.setFocusable(true);
        secondBtn.setFocusableInTouchMode(true);
        secondBtn.setId(R.id.sky_dialog_btn_2);
        secondBtn.setGravity(Gravity.CENTER);
        secondBtn.setSingleLine(true);
        secondBtn.setHorizontallyScrolling(true);
        secondBtn.setEllipsize(TruncateAt.MARQUEE);
        secondBtn.setMarqueeRepeatLimit(-1);
        secondBtn.setText(R.string.dialog_btn_2);
        secondBtn.setTextSize(
                SkyScreenParams.getInstence(mContext).getTextDpiValue(SkyTextSize.t_4));
        secondBtn.setTextColor(getResources().getColor(R.color.c_3));
        secondBtn.setOnKeyListener(onKeyListener);
        secondBtn.setOnClickListener(clickListener);
        secondBtn.setOnFocusChangeListener(changeListener);
        secondBtn.setBackground(SkyThemeEngine.getInstance()
                .getDrawable(R.drawable.ui_sdk_btn_unfocus_big_shadow, false));

        content = new LinearLayout(mContext);
        content.setFocusable(false);
        content.setOrientation(LinearLayout.VERTICAL);
        content.setGravity(Gravity.CENTER_HORIZONTAL);
        LayoutParams content_l_p = new LayoutParams(
                SkyScreenParams.getInstence(mContext).getResolutionValue(1061),
                SkyScreenParams.getInstence(mContext).getResolutionValue(492));
        contentView.addView(content, content_l_p);

        LinearLayout.LayoutParams tip_1_p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        tip_1_p.topMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(82);
        content.addView(tipsView_1, tip_1_p);
        tipsView_1.setMaxWidth(SkyScreenParams.getInstence(mContext).getResolutionValue(845));

        LinearLayout.LayoutParams tip_2_p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        tip_2_p.topMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(20);
        content.addView(tipsView_2, tip_2_p);

        LinearLayout btnLayout = new LinearLayout(mContext);
        btnLayout.setFocusable(false);
        btnLayout.setOrientation(LinearLayout.HORIZONTAL);
        btnLayout.setGravity(Gravity.CENTER);
        LayoutParams btnLayout_p = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                SkyScreenParams.getInstence(mContext).getResolutionValue(73)
                        + unfocusShaderSize * 2);
        btnLayout_p.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        btnLayout_p.bottomMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(85)
                - unfocusShaderSize;
        contentView.addView(btnLayout, btnLayout_p);

        LinearLayout.LayoutParams btn_first_p = new LinearLayout.LayoutParams(
                SkyScreenParams.getInstence(mContext).getResolutionValue(300)
                        + unfocusShaderSize * 2,
                SkyScreenParams.getInstence(mContext).getResolutionValue(73)
                        + unfocusShaderSize * 2);
        btnLayout.addView(firstBtn, btn_first_p);

        if (twoBtn)
        {
            LinearLayout.LayoutParams btn_second_p = new LinearLayout.LayoutParams(
                    SkyScreenParams.getInstence(mContext).getResolutionValue(300)
                            + unfocusShaderSize * 2,
                    SkyScreenParams.getInstence(mContext).getResolutionValue(73)
                            + unfocusShaderSize * 2);
            btn_second_p.leftMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(58)
                    - unfocusShaderSize * 2;
            btnLayout.addView(secondBtn, btn_second_p);
        }

        SkyDialogViewV1.this.setVisibility(View.GONE);
    }

    private void initAnim()
    {
        animSet = new AnimationSet(true);

        transAnim = new TranslateAnimation(0, 0,
                -SkyScreenParams.getInstence(mContext).getResolutionValue(495), 0);
        transAnim.setDuration(100);

        ScaleAnimation acquireFocusAnim = new ScaleAnimation(0.9f, 1.0f, 0.9f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        acquireFocusAnim.setFillAfter(true);
        acquireFocusAnim.setDuration(100);

        alphaAnim = new AlphaAnimation(0.0f, 1.0f);
        // alphaAnim.setDuration(200 * 3 / 2);
        alphaAnim.setDuration(100);

        // animSet.addAnimation(transAnim);
        animSet.addAnimation(acquireFocusAnim);
        animSet.addAnimation(alphaAnim);
    }

    @SuppressLint("RtlHardcoded")
    public void setTipsString(String tips_1, String tips_2)
    {
        if (tips_1 != null && !tips_1.equals(""))
        {
            tipsView_1.setText(tips_1);
            tipsView_1.post(new Runnable()
            {
                @Override
                public void run()
                {
                    setTextStyle();
                    tipsView_1.setVisibility(View.VISIBLE);
                }
            });
        } else
        {
            tipsView_1.setVisibility(View.GONE);
        }

        if (tips_2 != null && !tips_2.equals(""))
        {
            isTwoString = true;
            tipsView_2.setText(tips_2);
            tipsView_2.setVisibility(View.VISIBLE);
        } else
        {
            isTwoString = false;
            tipsView_2.setVisibility(View.GONE);
        }
    }

    private void setTextStyle()
    {
        if (tipsView_1.getWidth() >= SkyScreenParams.getInstence(mContext).getResolutionValue(845))
        {
            LinearLayout.LayoutParams tip_1_p = (LinearLayout.LayoutParams) tipsView_1
                    .getLayoutParams();
            if (isTwoString)
                tip_1_p.topMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(82);
            else
                tip_1_p.topMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(82);
            tip_1_p.width = SkyScreenParams.getInstence(mContext).getResolutionValue(845);
            tip_1_p.height = SkyScreenParams.getInstence(mContext).getResolutionValue(110);
            tipsView_1.setLayoutParams(tip_1_p);
            tipsView_1.setEllipsize(TruncateAt.END);

            LinearLayout.LayoutParams tip_2_p = (LinearLayout.LayoutParams) tipsView_2
                    .getLayoutParams();
            tip_2_p.width = SkyScreenParams.getInstence(mContext).getResolutionValue(845);
            tipsView_2.setLayoutParams(tip_2_p);
            tipsView_1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            tipsView_1.postInvalidate();
            tipsView_2.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            tipsView_2.postInvalidate();
        } else
        {
            LinearLayout.LayoutParams tip_1_p = (LinearLayout.LayoutParams) tipsView_1
                    .getLayoutParams();
            if (!isTwoString)
                tip_1_p.topMargin = SkyScreenParams.getInstence(mContext).getResolutionValue(143);
            tip_1_p.width = LayoutParams.WRAP_CONTENT;
            tip_1_p.height = LayoutParams.WRAP_CONTENT;
            tipsView_1.setLayoutParams(tip_1_p);

            LinearLayout.LayoutParams tip_2_p = (LinearLayout.LayoutParams) tipsView_2
                    .getLayoutParams();
            tip_2_p.width = LayoutParams.WRAP_CONTENT;
            tipsView_2.setLayoutParams(tip_2_p);
            tipsView_1.setGravity(Gravity.CENTER);
            tipsView_1.postInvalidate();
            tipsView_2.setGravity(Gravity.CENTER);
            tipsView_2.postInvalidate();

        }
    }

    public void setBtnFocus(int index)
    {
        mInitBtnFocusIndex = index;
    }

    public void setBtnString(String btn_1, String btn_2)
    {
        if (btn_1 != null && !btn_1.equals(""))
            firstBtn.setText(btn_1);
        if (btn_2 != null && !btn_2.equals(""))
            secondBtn.setText(btn_2);
    }

    /**
     * 概述：设置dialog显示动画类型,执行动画,动画时间
     *
     * @param duration 时间
     * @param type     类型
     * @date 2015-2-2
     */
    public void show()
    {
        // focusView.setVisibility(View.GONE);
        SkyDialogViewV1.this.setVisibility(View.VISIBLE);
        contentView.startAnimation(animSet);

        animSet.setAnimationListener(new AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
                if (twoBtn)
                {
                    if (mInitBtnFocusIndex == 0 && !firstBtn.hasFocus())
                    {
                        firstBtn.requestFocus();
                    } else if (mInitBtnFocusIndex == 1 && !secondBtn.hasFocus())
                    {
                        secondBtn.requestFocus();
                    }
                } else if (!firstBtn.hasFocus())
                {
                    firstBtn.requestFocus();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                // contentView.clearAnimation();
                // int[] location = new int[2];
                // firstBtn.getLocationOnScreen(location);
                // int posX = location[0]
                // - SkyScreenParams.getInstence(mContext).getResolutionValue(417);
                // int posY = location[1]
                // - SkyScreenParams.getInstence(mContext).getResolutionValue(282);
                // int destWidth = firstBtn.getWidth()
                // + SkyScreenParams.getInstence(mContext).getResolutionValue(47) * 2;
                // int destHeight = firstBtn.getHeight()
                // + SkyScreenParams.getInstence(mContext).getResolutionValue(47) * 2;
                // focusView.changeFocusPos(posX, posY, destWidth, destHeight);
                // uiHandler.sendEmptyMessageDelayed(0, 100);
                setTextStyle();
                // uiHandler.sendEmptyMessage(0);
                contentView.clearAnimation();
            }
        });
    }

    // Handler uiHandler = new Handler()
    // {
    // @Override
    // public void handleMessage(Message msg)
    // {
    // super.handleMessage(msg);
    // firstBtn.requestFocus();
    // // if (focusView.getVisibility() != View.VISIBLE)
    // // focusView.setVisibility(View.VISIBLE);
    // };
    // };

    public void dismiss()
    {
        SkyDialogViewV1.this.clearAnimation();
        // focusView.setVisibility(View.GONE);
        AnimationSet set = new AnimationSet(true);
        ScaleAnimation acquireFocusAnim = new ScaleAnimation(1.0f, 0.9f, 1.0f, 0.9f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        acquireFocusAnim.setFillAfter(true);
        acquireFocusAnim.setDuration(100);
        set.addAnimation(acquireFocusAnim);

        AlphaAnimation alphaAnim = new AlphaAnimation(1.0f, 0.0f);
        // alphaAnim.setDuration(200 * 3 / 2);
        alphaAnim.setDuration(100);
        alphaAnim.setFillAfter(true);
        set.addAnimation(alphaAnim);
        contentView.startAnimation(set);
        set.setAnimationListener(new AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                SkyDialogViewV1.this.setVisibility(View.GONE);
                SkyDialogViewV1.this.clearAnimation();
            }
        });

        tipsView_1.setText(" ");
        LinearLayout.LayoutParams tip_1_p = (LinearLayout.LayoutParams) tipsView_1
                .getLayoutParams();
        tip_1_p.width = LayoutParams.WRAP_CONTENT;
        tipsView_1.setLayoutParams(tip_1_p);

        tipsView_2.setText(" ");
        LinearLayout.LayoutParams tip_2_p = (LinearLayout.LayoutParams) tipsView_2
                .getLayoutParams();
        tip_2_p.width = LayoutParams.WRAP_CONTENT;
        tipsView_2.setLayoutParams(tip_2_p);
    }

    OnFocusChangeListener changeListener = new OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus)
        {
            ((TextView) v).setSelected(hasFocus);
            if (hasFocus)
            {
                ((TextView) v).setTextColor(getResources().getColor(R.color.a_5));
                v.setBackgroundResource(R.drawable.ui_sdk_shape_focus_white);
                focusView.changeFocusPos(v);
            } else
            {
                ((TextView) v).setTextColor(getResources().getColor(R.color.c_3));
                v.setBackground(SkyThemeEngine.getInstance()
                        .getDrawable(R.drawable.ui_sdk_btn_unfocus_big_shadow, false));
            }
        }
    };

    OnKeyListener onKeyListener = new OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
                {
                    if (twoBtn)
                    {
                        if (v.getId() == R.id.sky_dialog_btn_1)
                            return true;
                        else if (v.getId() == R.id.sky_dialog_btn_2)
                        {
                            firstBtn.requestFocus();
                            return true;
                        }
                    } else
                    {
                        if (v.getId() == R.id.sky_dialog_btn_1)
                            return true;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
                {
                    if (twoBtn)
                    {
                        if (v.getId() == R.id.sky_dialog_btn_2)
                            return true;
                        else if (v.getId() == R.id.sky_dialog_btn_1)
                        {
                            secondBtn.requestFocus();
                            return true;
                        }
                    } else
                    {
                        if (v.getId() == R.id.sky_dialog_btn_1)
                            return true;
                    }
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP
                        || keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                {
                    if (v.getId() == R.id.sky_dialog_btn_1 || v.getId() == R.id.sky_dialog_btn_2)
                    {
                        return true;
                    }
                } else if (mListener != null)
                {
                    return mListener.onDialogOnKeyEvent(keyCode, event);
                } else
                    return false;
            }
            return false;
        }
    };

    OnClickListener clickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.sky_dialog_btn_1)
            {
                if (mListener != null)
                    mListener.onFirstBtnOnClickEvent();
            } else if (id == R.id.sky_dialog_btn_2)
            {
                if (mListener != null)
                    mListener.onSecondBtnOnClickEvent();
            }

        }
    };

    @Override
    public void refreshOnThemeChanged()
    {
        if (tipsView_1 != null)
            tipsView_1.setTextColor(getResources().getColor(R.color.c_4));
        if (tipsView_2 != null)
            tipsView_2.setTextColor(getResources().getColor(R.color.c_3));
        if (firstBtn != null && !firstBtn.hasFocus())
        {
            firstBtn.setTextColor(getResources().getColor(R.color.c_3));
            firstBtn.setBackground(SkyThemeEngine.getInstance()
                    .getDrawable(R.drawable.ui_sdk_btn_unfocus_big_shadow, false));
        }
        if (secondBtn != null && !secondBtn.hasFocus())
        {
            secondBtn.setTextColor(getResources().getColor(R.color.c_3));
            secondBtn.setBackground(SkyThemeEngine.getInstance()
                    .getDrawable(R.drawable.ui_sdk_btn_unfocus_big_shadow, false));
        }
    }

    public void destroy()
    {
        if (blurBgLayout != null)
        {
            blurBgLayout.destroy();
        }
    }

    public void setTipsView_2_TextSize(int size)
    {
        tipsView_2.setTextSize(
                SkyScreenParams.getInstence(mContext).getTextDpiValue(size));

    }

}
